package leetcode;

import java.util.NoSuchElementException;

/**
 * 我的循环队列
 */
public class MyCircularQueue implements Queue<Integer> {
    private Integer[] cirQue;

    /**
     * 存储队列有效元素个数
     */
//    private int size;

    /**
     * head指向当前的队首元素
     */
    private int head;

    /**
     * rear指向当前的队尾元素的下一个
     */
    private int rear;

    /**
     * 设置队列大小
     * @param k
     */
    public MyCircularQueue(int k) {
        cirQue = new Integer[k + 1]; // 要始终让head和rear之间有一个空间，来区分判断满和空的条件
    }

    @Override
    public boolean enQueue(Integer value) {
        if (isFull()) {
//            throw new NoSuchElementException("queue is empty!cannot add!");
            return false;
        }
        cirQue[rear] = value;
        rear = (rear + 1) % cirQue.length;
        return true;
    }

    @Override
    public boolean deQueue() {
        if (isEmpty()) {
//            throw new NoSuchElementException("queue is empty!cannot delete!");
            return false;
        }
        head = (head + 1) % cirQue.length;
//        size --;
        return true;
    }

    @Override
    public int Front() {
        if (isEmpty()) {
            return -1;
//            throw new ArrayIndexOutOfBoundsException("queue is empty!cannot query!");
        }
        return cirQue[head];
    }

    @Override
    public int Rear() {
        if (isEmpty()) {
            return -1;
//            throw new ArrayIndexOutOfBoundsException("queue is empty!cannot query!");
        }
        return cirQue[(rear - 1 + cirQue.length) % cirQue.length];
    }

    @Override
    public boolean isEmpty() {
        if (head == rear) {
            return true;
        }
        return false;
    }

    @Override
    public boolean isFull() {
        if ((rear + 1) % cirQue.length == head) {
            return true;
        }
        return false;
    }

    /**
     * 查询队列长度
     * @return
     */
    public int size() {
        return (rear - head + cirQue.length) % cirQue.length;
    }
}

class Test2 {
    public static void main(String[] args) {
        MyCircularQueue myCircularQueue = new MyCircularQueue(5);
        for (int i = 0; i < 5; i++) {
            myCircularQueue.enQueue(i);
        }
        System.out.println(myCircularQueue);
        System.out.println(myCircularQueue.size());
    }
}
